package com.qingzhu.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.qingzhu.DefalutUrl;
import com.qingzhu.pojo.Login;
import com.qingzhu.pojo.User;
import com.qingzhu.pojovo.ResultVo;
import com.qingzhu.service.LoginAndRegisterService;
import com.qingzhu.service.impl.LoginAndRegisterServiceImpl;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.Converter;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Map;

@WebServlet("/login")
public class LoginAndRegisterController extends HttpServlet {
    LoginAndRegisterService loginAndRegisterService = new LoginAndRegisterServiceImpl();
    ObjectMapper objectMapper = new ObjectMapper();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("用户登陆..");

        String server = req.getParameter("server");
        if (server.equals("login")) {
            login(req,resp);
        }else if (server.equals("signOut")) {
            signOut(req,resp);
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("用户注册..");
        // 获取前端表单传递过来的所有数据
        Map<String, String[]> data = req.getParameterMap();
        // 处理日期格式的数据
        ConvertUtils.register(new Converter() {
            @Override
            public Object convert(Class aClass, Object o) {
                // 如果字符串为null，则返回null
                if(o == null)
                    return null;

                // 如果字符串为空格，则返回null
                String str = (String) o;
                if(str.trim().equals(""))
                    return null;

                // 将字符串转为Date类型
                SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
                try {
                    return formatter.parse(o.toString());
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                return new Date();
            }
        }, Date.class);
        // 数据封装
        User user = new User();
        try {
            BeanUtils.populate(user, data);
            // 获取当前时间
            Calendar calendar = Calendar.getInstance();
            user.setCreated(calendar.getTime());
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("注册信息预览："+user);
        // 添加用户信息
        loginAndRegisterService.toRegister(user);
        // 获取访问地址
        String origin = req.getHeader("Origin");
        resp.sendRedirect(origin+"/login.html");
    }


    // 登录验证
    public void login(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
        String nameOrPhone = req.getParameter("phone");
        String password = req.getParameter("password");
        Login login = loginAndRegisterService.login(nameOrPhone, password);
        if (login.getLoginCode() == 0) {
            // 将用户信息储存到项目域
            ServletContext servletContext = req.getServletContext();
            servletContext.setAttribute("login",login);
            resp.getWriter().write(objectMapper.writeValueAsString(new ResultVo(200,"登录成功！",login)));
        }else {
            resp.getWriter().write(objectMapper.writeValueAsString(new ResultVo(1000,login.getMessage())));
        }
    }
    /* 退出登录 主要功能是清空session域中储存的id */
    public void signOut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
        req.getServletContext().removeAttribute("login");
        System.out.println("登录信息已经销毁！");
        resp.getWriter().write(objectMapper.writeValueAsString(new ResultVo(200,"成功退出登录！")));
    }
}